package com._21cn._front.utils.uc;

import com._21cn.cms.common.Constants;
import com._21cn.cms.site.entity.Config;
import com._21cn.cms.site.service.ConfigService;
import com._21cn.framework.cache.Cache;
import com._21cn.framework.cache.SimpleCache;
import com._21cn.framework.utils.StringUtil;
import com.uctoutiao.openapi.sdk.auth.AuthRequest;
import com.uctoutiao.openapi.sdk.exception.OpenApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component("ucTokenHelper")
public class UcTokenHelper {

    private Cache cache = new SimpleCache().init();

    private String tokenKey = "UC_TOKEN";
    private Integer tokenSeconds = 7*24*60*60;

    @Autowired
    private ConfigService configService;

    /**
     * 更新token
     * @param token
     */
    public void updateToken( String token ){
        if (!StringUtil.isEmpty(token)) {
            //1、更新缓存
            cache.put(tokenKey, token, tokenSeconds);
            //2、更新数据库
            Config config = configService.getConfig(Constants.DEFAULT_SITE_ID, 0, 0, tokenKey);
            config.setValue(token);
            config.setModifyTime(new Date());
            configService.update(config);
        }
    }

    /**
     * 请求token
     */
    public boolean reqToken() {
        boolean result = false;
        try {
            AuthRequest req = new AuthRequest();
            result = req.getAccessToken(AppConfig.APP_ID, AppConfig.SECRET);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取token
     * @return
     */
    public String getToken(){
        String token = (String)cache.get(tokenKey);
        if(StringUtil.isEmpty(token)){
            Config config = configService.getConfig(Constants.DEFAULT_SITE_ID, 0, 0, tokenKey);
            token = config.getValue();
            reqToken();      //请求token
        }
        return token;
    }
}
